///
/// Turn this variable to false if just running UI
var queryServer = true;
/// Turn this variable to false if just running UI
///
getChildrenScripts('rpp');

function getFieldSelection(appName, factName,paramid,callback) {
    var updateid = null;
	//if(!queryServer)return;
    if(isNull(paramid))
    {
       updateid = getParameterByName('id')
    }
    else
    {
        updateid=paramid;
    }
    if(isNull(updateid)==false) // updateid isnt null
    {
        var hiddenId = $('<input type=hidden id=updateid name=updateid value='+updateid+' />')
        $('form').append(hiddenId);
        loadUpdateData(appName,factName,updateid);
    }
    // Find all children within the form that have the "select" tag
	var lookupSelector = 'select';
    var len = $(lookupSelector).length;
    var count = 0;
    $(lookupSelector).each(function(){
         var thisDom = $(this);
         var domId = thisDom.attr("id");
         // Asynchronously get the fields from the controller 
         var get_callback=$.get('/quickforms/getFieldSelection', // Controller url
            {app:appName,factTable:factName,field:domId,updateid:updateid}, // controller parameters
            function(data)
			{
                if(data != "")
				{
                    // replace the current select dom elements with the JSON supplied from the controller
                    if (thisDom[0].tagName == 'SELECT') 
                    {
						if(isJSONString(data))
						{
							thisDom.children().remove();
							var json = JSON.parse(data);
							for(i=0;i<json.length;i++)
							{
								thisDom.append($('<option value='+json[i].id+' '+json[i].selected+'>'+json[i].label+'</option>'));
							}
							
							count += 1;
							if(count == len)
							{
								//$.getScript('js/jquery.mobile-1.1.1.min.js');  /// add the jquery mobile api after inserting 
								/// required or else css will not be applied to the select tags.
								callback();
								//$('form').trigger('create');
							}
						}
						else
						{
							alertJSONError(data);
						}
					}
                    else if(thisDom[0].tagName == 'UL')
					{
                       convertJSONtoUl(thisDom,data,domId);
					}
					
                    if(thisDom.hasClass('combobox'))
					{
                        convertJSONtoComboBox(thisDom,data,domId);
					}
                    else if(thisDom.hasClass('autocomplete'))
					{
                        convertJSONtoAutoComplete(thisDom,data,domId);
					}
                    
                }
              });
          get_callback.fail(function(e1,e2,e3) 
		  { 
                        console.log(e1+e2+e3);
			count += 1;
			if(count == len){
                            $('form').trigger('create');    
							callback();
			}
		  });
      }); 
      
    var myDate = new Date();
    var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
    myDate.getFullYear();
    $( ".date" ).val(prettyDate);
    $( ".date" ).datepicker();
    $(".birthdate").datepicker({ yearRange: '-105:+1',changeYear: true });
}
function convertJSONtoSelect(thisDom, data)
{
    if(isJSONString(data)){
		thisDom.children().remove();
        var json = JSON.parse(data);
        for(i=0;i<json.length;i++)
        {
            thisDom.append($('<option value='+json[i].id+' '+json[i].selected+'>'+json[i].label+'</option>'));
        }
        thisDom.selectmenu('refresh', true);
    }
    else
    {
        alertJSONError(data);
    }
}
function convertJSONtoUl(thisDom, data, domId)
{
    if(isJSONString(data)){
		thisDom.children().remove();
        var json = JSON.parse(data);
        for(i=0;i<json.length;i++)
        {
            thisDom.append($('<LI value='+json[i].id+'> <a href="#dialog_' + domId + '_' + json[i].id + '" data-rel="dialog">'+json[i].label+'</a></LI>'));
        }
        thisDom.listview('refresh');
    }
    else
    {
        alertJSONError(data);
    }
}
function convertJSONtoComboBox(thisDom, data, domId)
{
    if(isJSONString(data))
    {
        var json=JSON.parse(data);
        $('<ul id="'+domId+'_target" data-role="listview" data-inset="true" data-theme="b" ></ul>').insertAfter('#'+domId);
        $('#'+domId+'_target').listview();
        thisDom.autocomplete({
                source: json,
                target: $('#'+domId+'_target'),
                callback: function(e) {
                    var selected = $(e.currentTarget);
                    thisDom.val(selected.html());
                    thisDom.autocomplete('clear');
                },
                minLength: 0
        });
        thisDom.click(function(e)
        {
            if($('#'+domId+'_target').children().length<=0)
                thisDom.keyup();
            else
                $('#'+domId+'_target').html('');
        });
    }
}
function convertJSONtoAutoComplete(thisDom, data, domId)
{
    if(isJSONString(data))
    {
        var json=JSON.parse(data);
        $('<ul id="'+domId+'_target" data-role="listview" data-inset="true" data-theme="b" ></ul>').insertAfter('#'+domId);
        $('<input type="hidden" name ="'+domId+'" value="1" id="'+domId+'_hidden"/>').insertAfter('#'+domId);
        $(json).each(function(i,row){
            if(row.selected == 'selected')
            {
				if(row[domId+'_order']>1)
				{
					$('#'+domId+'_hidden').val(row.id);
					thisDom.val(row.label);
				}
            }
        });
        $('#'+domId).attr('name','unused');
        $('#'+domId+'_target').listview();
        thisDom.autocomplete({
                source: json,
                target: $('#'+domId+'_target'),
                callback: function(e) {
                    var selected = $(e.currentTarget);
                    thisDom.val(selected.html());
                    $('#'+domId+'_hidden').val(JSON.parse($(e.target).attr('data-autocomplete')).id);
                    thisDom.autocomplete('clear');
                },
                minLength: 3
        });
        thisDom.click(function(e)
        {
            if($('#'+domId+'_target').children().length<=0)
			{
                thisDom.keyup();
				thisDom.select();
			}
            else
                $('#'+domId+'_target').html('');
        });
    }
}
function getResultSet(appName, queryLab, prms, callback) {
	$.ajax({
	  type: 'GET',
	  url: '/quickforms/getResultSet',
	  data: {app:appName,queryLabel: queryLab, params : prms},
	  success: function(data,status,xhr){
			// return the json data back to the form specific controller
			callback(data);
	  },
	  error: function(xhr, status, e){
	  callback('Error: '+e);
	  }
	});
}
function executeQuery(appName, queryLab, prms, callback) {
	$.ajax({
	  type: 'GET',
	  url: '/quickforms/executeQuery',
	  dataType: 'html',
	  data: {app:appName,queryLabel: queryLab, params : prms},
	  success: function(data,status,xhr){
			// return the json data back to the form specific controller
			callback(data);
	  },
	  error: function(xhr, status, e){
		callback('Error: '+e);
	  }
	});
}
function loadTableData(appName,factName, queryName, parameterList, callback)
{
    getResultSet(appName,queryName,parameterList,
        function(data){
            if(isJSONString(data))
            {
                var json = JSON.parse(data); 
                var liProto = $('#mainData li');
                for(i=0;i<json.length-1;i++)
                {
                    var liNew = liProto.clone();
                    liNew.appendTo('#mainData');
                }
				
                for(i=0;i<json.length;i++)
                {   
                   // var thisLi = $('#mainData li').eq(i);
                   var updateLink = $('#mainData li:eq('+i+') a');
                   var liHandle = $('#mainData li:eq('+i+')');
                   var leafHandle = $('#mainData li:eq('+i+') td:not(:has(*))');
                   var updateHref=updateLink.attr('href')+'?id='+json[i]['id'];
                   
                   updateLink.attr('href',updateHref); // add the id to the update link
                   updateLink.children('table').attr('onclick',"window.location='"+updateHref+"'"); 
                   // Must make the table have an on click because IE sucks
                   
                   liHandle.attr('id',json[i]['id']); // add the data id to the li row
                   liHandle.append('<input type=hidden value='+json[i]['id']+'>');
                   
                   leafHandle.each(function(){ // find each leaf node and replace it with data
                           if($(this).attr('id')!= null)
                           {
                                $(this).html('');
                                $(this).append(json[i][$(this).attr('id')]);
                           }
                    });
                }
            }
            else
            {
				$('#mainData').remove();
                alertJSONError(data);
            }
             //$.getScript('js/jquery.mobile-1.1.1.min.js');  /// add the jquery mobile api after loading lookups 
                        /// required or else css will not be applied to the <li>
             $('form').trigger('create');
             callback();
        }
    );
    if(getParameterByName("insertedRow")=="true")
    {
        window.setTimeout(function(){highlightMostRecent()},500);
    }
}
function highlightMostRecent()
{
        //var liProto = $('#mainData li:eq(0)');
        var updatedId = getParameterByName('id');
        $('#mainData li#'+updatedId).effect("highlight", {}, 2000);
}
function putFact (appName, factName, location)
{
    //// append the information about the app and the fact table to the form
    $('<input />').attr('type', 'hidden')
            .attr('name', 'app')
            .attr('value', appName)
            .appendTo('form');
    $('<input />').attr('type', 'hidden')
            .attr('name', 'factTable')
            .attr('id', 'factTable')
            .attr('value', factName)
            .appendTo('form');
    var username=getCookie('username');
    $('<input />').attr('type', 'hidden')
            .attr('name', 'added_by')
            .attr('value', username)
            .appendTo('form');    
            
	$.ajax({
	  type: 'POST',
	  url: '/quickforms/putFact',
	  data: $('form').serialize(),
	  success: function(data,status,xhr){
            saveComboboxValues(appName);
            var json;
            if(isJSONString(data))
            {
                    json = JSON.parse(data);
                    window.location.href = location +'?insertedRow=true&id='+json[0]['id'];
            }
            else
            {
                    //window.alert("Row not saved : "+data);
            }
	  },
	  error: function(xhr, status, e){
            if(queryServer)
            {
               //window.alert("Row not saved, could not connect to server: "+e);
               alertJSONError(e);
            }
            else
            {
               window.location.href = location;
            }
	  }
	});
      
    return false;
}
function saveComboboxValues(appName)
{
    $('.combobox').each(function(i,dom){
        $.ajax({
                type: 'POST',
                async: false,
                cache: false,
                timeout: 3000,
                url: '/quickforms/putComboBox',
                data: {app:appName,lookupTable: $(dom).attr('id'), value : $(dom).val()},
                success: function(data,status,xhr){
                    console.log(data);
                },
                error: function(data,status,xhr){
                    console.log(data+" "+xhr);
                }
        });
    });
}
function loadReportInTable(appName,factName, queryName, parameterList)
{
    getResultSet(appName,queryName,parameterList,
        function(data){
            if(isJSONString(data))
            {
                var json = JSON.parse(data); 
                var liProto = $('#'+queryName+' table tbody tr');
                for(i=0;i<json.length-1;i++)
                {
                    var liNew = liProto.clone();
                    liNew.appendTo('#'+queryName+' table tbody');
                }

                for(i=0;i<json.length;i++)
                {   
                   var leafHandle = $('#'+queryName+' table tbody tr:eq('+i+') td:not(:has(*))');

                   leafHandle.each(function(){ // find each leaf node and replace it with data
                           if($(this).attr('id')!= null)
                           {
                                $(this).html('');
                                $(this).append(json[i][$(this).attr('id')]);
                           }
                    });
                }
            }
            else
            {
                alertJSONError(data);
            }
            // $.getScript('js/jquery.mobile-1.1.1.min.js');  /// add the jquery mobile api after loading lookups 
                        /// required or else css will not be applied to the <li>s
        }
    );
}
function loadUpdateData(appName,factName,updateid,callback)
{
    getResultSet(appName, factName+'_get_row', 'updateid='+updateid, function(data){
        if(isJSONString(data)){
            var json = JSON.parse(data);
            $('form').find('input,textarea,checkbox,radio').each(function(){
                var thisDom = $(this);
				var val = json[0][thisDom.attr('id')];
			//	if(thisDom.hasClass('date') || thisDom.hasClass('birthdate'))
			//		val = val.split(" ")[0];
			if(thisDom.attr('type') == "checkbox")
			{
				if(val == "1")
				thisDom.attr('checked',true).checkboxradio();
			}
			else if(thisDom.attr('type') == "radio")
			{
			if(json[0][thisDom.attr("name")] == "1")
			{
			$('input:radio[name=' + thisDom.attr("name") + ']')[0].checked = true;
			$('input:radio[name=' + thisDom.attr("name") + ']').checkboxradio();
			}
			}
			else
			{
                		thisDom.attr('value',val);
			}
            });
		if($('select').length == 0 && isNull(callback)==false)
		{
			callback();
		}
        }
        else
        {
            alertJSONError(data);
        }
    });
}
function getChildrenScripts(root)
{
	$.ajaxSetup({ cache: false });
    $.ajaxSetup({async: false});
    $.getScript('/'+root+'/js/quickforms-helpers.js');
    $.getScript('/'+root+'/js/jqm.autoComplete.js');
	$.getScript('/'+root+'/js/json2.js');
	$.getScript('/'+root+'/js/md5.js');
	$.getScript('/'+root+'/js/session.js');
    $.ajaxSetup({async: true});
}
$(document).bind("mobileinit",function(){
    $.mobile.loadingMessage = false;//Finally works now that initializePage is removed

    //Specific for Android's flashing page 
    $.mobile.defaultDialogTransition = 'none';
	$.mobile.defaultPageTransition = 'none';
})



function loadTabularData(appName,factName, queryName, parameterList, callback)
{
	
	getResultSet(appName,queryName,parameterList,
        function(data){
            if(isJSONString(data))
            {
                var json = JSON.parse(data); 
               // var aaData = {"aaData":json};
				var columns = [];
				for(var key in json[0])
				{
					var obj = { sTitle: key , mData: key};
					if(key == "id" || key == "form")
						obj = { sTitle: key , mData: key, bVisible: false};
						
					 columns.push(obj);
				} 
                
                
                var oTable = $('#mainData').dataTable( {  
                	"sDom":'<"top"lfi>rt<"bottom"ip<"clear">',
            		"bProcessing": true,
            		"iDisplayLength": 50,
            		"sPaginationType": "full_numbers",
            		"aaSorting": [[0,"desc"]],	
            		"aaData": json,
//	            	"aoColumns": [     	         
//	            		       { "sTitle": "Date",   "mData": "date" },
//	            		       { "sTitle": "Location",  "mData": "location" },
//	            		       { "sTitle": "Notes", "mData": "notes" },
//	            		       { "sTitle": "Age",  "mData": "age" },
//	            		       { "sTitle": "Gender",    "mData": "gender" },
//	            		       { "sTitle": "ID",   "mData": "id" ,   "bVisible": false }
//	            		 ],
            		"aoColumns": columns,
	  //               "fnCreatedRow": function( nRow, aData, iDataIndex ) {	
	    //             }
	     "sDom":'<"top"lf<"clear">ip<"clear">>rt<"bottom"ip<"clear">'            
            	} );	
              
                
                // make the row clickable
                $('#mainData tbody tr').click( function () {
                    var aData = oTable.fnGetData( this );
                    //alert( aData.id ); // assuming the id is in the first column
                    window.location = aData.form+".html?id="+ aData.id;
                } );
               
                
            }
            else
            {
				$('#mainData').remove();
                alertJSONError(data);
            }
             //$.getScript('js/jquery.mobile-1.1.1.min.js');  /// add the jquery mobile api after loading lookups 
                        /// required or else css will not be applied to the <li>
             $('form').trigger('create');
             callback();
        }
    );
    if(getParameterByName("insertedRow")=="true")
    {
        window.setTimeout(function(){highlightMostRecent()},500);
    }
}

